<#
注入风险扫描（原生 PowerShell）
用途：扫描 Python/Java 代码中可能的注入风险模式（eval/exec/shell=True/SQL 拼接/Statement）。
用法：
  pwsh -File scripts/windows/check-injection.ps1
#>
param()

$WindowsDir = Split-Path -Parent $PSCommandPath
$ScriptsDir = Split-Path -Parent $WindowsDir
$RepoDir = Split-Path -Parent $ScriptsDir

$pyDir = Join-Path $RepoDir 'src/main/python'
$javaDir = Join-Path $RepoDir 'src/main/java'

$issues = @()

function Scan-File([string]$path, [string]$regex, [string]$desc) {
  $txt = Get-Content -Raw $path -ErrorAction SilentlyContinue
  if ($null -ne $txt -and ($txt -match $regex)) { $GLOBALS:issues += "[$desc] $path" }
}

if (Test-Path $pyDir) {
  Get-ChildItem -Path $pyDir -Recurse -File -Include *.py | ForEach-Object {
    Scan-File $_.FullName '(?mi)\beval\(' 'Python eval'
    Scan-File $_.FullName '(?mi)\bexec\(' 'Python exec'
    Scan-File $_.FullName '(?mi)shell\s*=\s*True' 'Python shell=True'
    Scan-File $_.FullName '(?mi)\b(SELECT|INSERT|UPDATE)\b.*\+' 'Python SQL 拼接'
  }
}

if (Test-Path $javaDir) {
  Get-ChildItem -Path $javaDir -Recurse -File -Include *.java | ForEach-Object {
    Scan-File $_.FullName '(?mi)\bjava\s*\.\s*sql\s*\.\s*Statement\b|\bcreateStatement\b' 'Java Statement'
    Scan-File $_.FullName '(?mi)execute(Query|Update)\(\s*".*"\s*\+' 'Java SQL 字符串拼接'
  }
}

if ($issues.Count -gt 0) {
  Write-Warning "发现潜在注入风险："
  $issues | ForEach-Object { Write-Host " - $_" }
  exit 2
} else {
  Write-Host "注入风险扫描通过"
  exit 0
}
